package com.ruoyi.framework.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;

@Configuration
@Slf4j
public class SslConfig {

    @Value("${server.ssl.trust-store-password}")
    private String trustStorePassword;

    @Value("${server.ssl.trust-store-type:JKS}")
    private String trustStoreType;

    @Value("${server.ssl.enabled:false}")
    private boolean sslEnable;

    public SSLContext createSSLContext() {
        if(sslEnable){
            try {
                KeyStore trustStore = KeyStore.getInstance(trustStoreType);
                try (InputStream is = getClass().getClassLoader().getResourceAsStream("certs/ruoyi-truststore.jks")) {
                    if (is == null) {
                        throw new FileNotFoundException("Could not find truststore.jks in classpath.");
                    }
                    trustStore.load(is, trustStorePassword.toCharArray());
                }

                TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                tmf.init(trustStore);

                SSLContext sslContext = SSLContext.getInstance("TLS");
                sslContext.init(null, tmf.getTrustManagers(), null);
                SSLContext.setDefault(sslContext);
                return sslContext;
            }catch (Exception e){
                log.error("SSLContext初始化失败", e);
            }
        }
        try {
            return SSLContext.getDefault();
        } catch (NoSuchAlgorithmException e) {
            log.error("SSLContext初始化失败", e);
        }
        return null;
    }

    @Bean
    @Lazy(false)
    public SSLContext sslContext() {
        return createSSLContext();
    }

}